const fs = require('fs');
const sd = require('silly-datetime');

exports.deleteFile = function (filePath) {
    fs.unlink(filePath, function (err) {
        if (err) {
            throw err;
        }
        console.log('文件:' + filePath + '删除成功！');
    })
}

exports.parseUrl = function (owner, repo, startTime) {
    if (startTime) {
        const endTime = sd.format(new Date(), 'YYYY-MM-DD');
        return `https://gitee.com/${owner}/${repo}/statistic?type=Star&start_date=${startTime}&end_date=${endTime}`;
    }
    return `https://gitee.com/${owner}/${repo}/statistic?type=Star`;
}

exports.writeImgToResponse = function (data, res) {
    const that = this
    const fileName = new Date().getTime() + '.png';
    fs.writeFile(fileName, new Buffer(data, 'base64'), function () {
        res.set('content-type', "image/gif");//设置返回类型
        const stream = fs.createReadStream(fileName);
        let responseData = [];
        if (stream) {
            stream.on('data', function (chunk) {
                responseData.push(chunk);
            });
            stream.on('end', function () {

                that.deleteFile(fileName);

                res.write(Buffer.concat(responseData));
                res.end();
            });
        } else {
            that.deleteFile(fileName);
        }
    });
}